package cn.monkey.transport.netty;

import cn.monkey.transport.core.Connection;
import io.netty.channel.*;
import io.netty.util.AttributeKey;
import reactor.core.publisher.Mono;

public interface NettyConnection extends Connection, NettyInbound, NettyOutbound {

    @Override
    default boolean isActive() {
        return this.channel().isActive();
    }

    @Override
    default Mono<Void> close() {
        ChannelFuture channelFuture = this.channel().close();
        return Mono.create(sink -> channelFuture.addListener((ChannelFutureListener) future -> {
            if (!future.isSuccess()) {
                sink.error(future.cause());
            }
            sink.success();
        }));
    }

    @Override
    default Connection bind() {
        this.channel().attr(AttributeKey.valueOf(Connection.class, Connection.KEY)).set(this);
        return this;
    }
}
